﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Security.Cryptography;
using DevExpress.XtraEditors;

namespace PRE.Catalog
{
    public partial class FrmUser : PRE.Catalog.FrmBase
    {

        #region Variable
        DAL.EntitiesDAL.UserDAL _dal = new DAL.EntitiesDAL.UserDAL();
        BLL.EntitiesBLL.UserBLL _bll = new BLL.EntitiesBLL.UserBLL();
        DAL.EntitesDAL.VaitroDAL _dal1 = new DAL.EntitesDAL.VaitroDAL();
        DataTable _dtb = new DataTable();
        DataTable _dtb1 = new DataTable();
        #endregion

        #region Inits
        public FrmUser()
        {
            InitializeComponent();
        }
        #endregion

        #region Override

        /// <summary>
        /// Perform when click add button
        /// </summary>
        protected override void PerformAdd()
        {
            ReadOnlyControl(false);
            ClearDataBindings();
            ChangeStatus(false);
            lbl_TenFile.Visible = true;
            txt_TenFile.Visible = true;
            ResetText();
            txtUser.Focus();

            base.PerformAdd();
        }

        /// <summary>
        /// Perform when click cancel button
        /// </summary>
        protected override void PerformCancel()
        {
            ChangeStatus();
            PerformRefresh();
            base.PerformCancel();
        }

        /// <summary>
        /// Perform when click delete button
        /// </summary>
        /// <returns></returns>
        protected override void PerformDelete()
        {
            txt_TenFile.Visible = false;
            lbl_TenFile.Visible = false;

            var tmp = gridView_User.GetFocusedRowCellValue("Id") + "";
            var _id = UTL.Number.ToInt64(tmp);

            DialogResult result;
            var ok = _dal.Delete(_id);
            result = XtraMessageBox.Show("Bạn có chắc xóa không ? ", "Thông Báo", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);
            if (result == DialogResult.OK)
            {
                if (ok)
                {
                    PerformRefresh();
                }
                else
                    XtraMessageBox.Show("Lỗi! Không xóa được", "Thông Báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            
            base.PerformDelete();
        }

        /// <summary>
        /// Perform when click edit button
        /// </summary>
        protected override void PerformEdit()
        {
            ReadOnlyControl(false);
            txtUser.Focus();
            txt_TenFile.Visible = true;
            lbl_TenFile.Visible = true;
            txtPass.Properties.ReadOnly = true;
            base.PerformEdit();
        }

        /// <summary>
        /// Perform when click print button
        /// </summary>
        protected override void PerformPrint()
        {
            base.PerformPrint();
        }

        /// <summary>
        /// Load data or perform when click refresh button
        /// </summary>
        protected override void PerformRefresh()
        {
            txt_TenFile.Visible = false;
            lbl_TenFile.Visible = false;

            ReadOnlyControl();
            LoadData();
            ChangeStatus();
            btnGoSearch.Visible = false;

            //VisibilityControl();

            if (_dtb != null)
            {
                // Binding data
                ClearDataBindings();
                if (_dtb.Rows.Count > 0) DataBindingControl();
            }

            base.PerformRefresh();
        }

        /// <summary>
        /// Perform when click save button
        /// </summary>
        protected override void PerformSave()
        {
            var name = Proper(txtName.Text);
            string tenFileAnh = txt_TenFile.Text.Trim();

            if (IsAdd)
            {
                var o = new DAL.Entities.User()
                {
                    Ten = txtUser.Text,
                    Matkhau = _bll.EncodeMD5(txtPass.Text),
                    Hoten = name,
                    VaitroID = Convert.ToInt32(cboRole.EditValue),
                    Images = tenFileAnh
                };

                var oki = _dal.Insert(o);
                if (oki)
                {
                    XtraMessageBox.Show("Đã lưu thành công", "Thông Báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    PerformRefresh();
                    ChangeStatus(false);
                    //PerformAdd();

                    txt_TenFile.Visible = false;
                    lbl_TenFile.Visible = false;
                }
                else
                {
                    XtraMessageBox.Show("Lỗi! Lưu thất bại", "Thông Báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    ChangeStatus(false);
                    ReadOnlyControl(false);
                }

            }

            if (IsEdit)
            {
                var tmp = gridView_User.GetFocusedRowCellValue("Id") + "";
                var _id = UTL.Number.ToInt32(tmp);

                var o = new DAL.Entities.User()
                {
                    Id = _id,
                    Ten = txtUser.Text,
                    Matkhau = _bll.EncodeMD5(txtPass.Text),
                    Hoten = name,
                    VaitroID = Convert.ToInt32(cboRole.EditValue),
                    Images = tenFileAnh
                };

                var oki = _dal.Update(o);
                if (oki)
                {
                    XtraMessageBox.Show("Đã lưu thành công", "Thông Báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    PerformRefresh();
                    ChangeStatus();

                    txt_TenFile.Visible = false;
                    lbl_TenFile.Visible = false;
                }
                else
                {
                    XtraMessageBox.Show("Lỗi! Lưu thất bại", "Thông Báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    ChangeStatus(false);
                    ReadOnlyControl(false);
                }
            }


            base.PerformSave();
        }

        /// <summary>
        /// Reset all input control
        /// </summary>
        protected override void ResetText()
        {
            txtUser.Text = null;
            txtPass.Text = null;

            txtName.Text = null;

            base.ResetText();
        }

        /// <summary>
        /// Clear data binding
        /// </summary>
        protected override void ClearDataBindings()
        {
            txtUser.DataBindings.Clear();
            txtPass.DataBindings.Clear();
            txtName.DataBindings.Clear();
            cboRole.DataBindings.Clear();
            txt_FileName.DataBindings.Clear();

            base.ClearDataBindings();
        }

        /// <summary>
        /// Add data binding
        /// </summary>
        protected override void DataBindingControl()
        {
            txtUser.DataBindings.Add("EditValue", _dtb, ".Ten");
            txtPass.DataBindings.Add("EditValue", _dtb, ".Matkhau");
            txtName.DataBindings.Add("EditValue", _dtb, ".Hoten");
            cboRole.DataBindings.Add("EditValue", _dtb, ".VaitroID");
            txt_FileName.DataBindings.Add("EditValue", _dtb, ".Images");

            base.DataBindingControl();
        }

        /// <summary>
        /// Set read only control on form
        /// </summary>
        /// <param name="isReadOnly">Read only is trule else normal</param>
        protected override void ReadOnlyControl(bool isReadOnly = true)
        {
           
            txtUser.Properties.ReadOnly = isReadOnly;
            txtPass.Properties.ReadOnly = isReadOnly;
            txtName.Properties.ReadOnly = isReadOnly;
            cboRole.Properties.ReadOnly = isReadOnly;

            gridControl_User.Enabled = isReadOnly;

            base.ReadOnlyControl(isReadOnly);
        }

        protected override void PerformSearch()
        {
            ReadOnlyControl(false);
            ClearDataBindings();
            ResetText();
            ChangeStatus(false);
            btnGoSearch.Visible = true;
            gridControl_User.Enabled = true;

            base.PerformSearch();
        }

        /// <summary>
        /// Execute Search data
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>

        private void btnGoSearch_Click_1(object sender, EventArgs e)
        {
            txt_TenFile.Visible = false;
            lbl_TenFile.Visible = false;

            string name = Proper(txtName.Text);
            var o = new DAL.Entities.User()
            {
                Ten = txtUser.Text,
                Matkhau = _bll.EncodeMD5(txtPass.Text),
                Hoten = name,
                VaitroID = Convert.ToInt32(cboRole.EditValue)
            };
           
        }

        /// <summary>
        /// Update object
        /// </summary>
        /// <returns>True if successful else false</returns>
        protected override bool UpdateObject()
        {
            return base.UpdateObject();
        }

        /// <summary>
        /// Insert object
        /// </summary>
        /// <returns>True if successful else false</returns>
        protected override bool InsertObject()
        {
            return base.InsertObject();
        }

        /// <summary>
        /// Load data
        /// </summary>
        protected override void LoadData()
        {
            try
            {
                _dtb = _dal.Select();
                _dtb1 = _dal1.Select();
                cboRole.Properties.DataSource = _dtb1;

                if (_dtb != null)
                {
                    gridControl_User.DataSource = _dtb;

                    try
                    {
                        string fileName = gridView_User.GetFocusedDataRow()["Images"].ToString();
                        pic_Hinh.Image = Image.FromFile(fileName);
                        pic_Hinh.SizeMode = PictureBoxSizeMode.StretchImage;
                    }
                    catch { }

                    AppGridView.SummaryField(gridView_User, "Ten", "Tổng = {0:#,0}", DevExpress.Data.SummaryItemType.Count);

                    gridView_User.Columns["Id"].Visible = false;
                    gridView_User.Columns["Images"].Visible = false;

                    gridView_User.OptionsBehavior.ReadOnly = true;
                    gridView_User.OptionsView.ColumnAutoWidth = true;

                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show("Lỗi : " + ex.Message, "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            base.LoadData();
        }
      

        #region Function
        private void txt_TenFile_Click(object sender, EventArgs e)
        {
            OpenFileDialog FileAnh = new OpenFileDialog();
            FileAnh.Filter = "JPeg Image|*.jpg|Bitmap Image|*.bmp|Gif Image|*.gif";
            FileAnh.ShowDialog();


            txt_TenFile.Text = FileAnh.FileName;
        }
        #endregion

        #endregion

        #region private void gridView_User_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        private void gridView_User_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            try
            {
                string fileName = gridView_User.GetFocusedDataRow()["Images"].ToString();
                pic_Hinh.Image = Image.FromFile(fileName);
                pic_Hinh.SizeMode = PictureBoxSizeMode.StretchImage;              
            }
            catch { }
        }
        #endregion

    }
}
